import { computed } from 'vue'
import { createTwoFilesPatch, parsePatch } from 'diff'
import { html } from 'diff2html'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

export interface DiffStats {
  additions: number
  deletions: number
  changes: number
}

export function useDiffCalculator(
  leftContent: () => string,
  rightContent: () => string,
  outputFormat: () => 'side-by-side' | 'line-by-line',
) {
  // 计算差异统计 - 使用 diff 库的细粒度对比
  const diffStats = computed<DiffStats>(() => {
    const left = leftContent()
    const right = rightContent()

    if (!left || !right) {
      return { additions: 0, deletions: 0, changes: 0 }
    }

    try {
      // 生成 patch
      const patch = createTwoFilesPatch('原始文档', '修改文档', left, right, '', '', {
        context: 0,
      })

      // 解析 patch 获取详细统计
      const parsedPatch = parsePatch(patch)
      let additions = 0
      let deletions = 0
      let changes = 0

      if (parsedPatch.length > 0) {
        const hunks = parsedPatch[0].hunks

        for (const hunk of hunks) {
          for (const line of hunk.lines) {
            if (line.startsWith('+')) {
              additions++
            } else if (line.startsWith('-')) {
              deletions++
            }
          }
        }

        // 计算修改行数（成对的删除和添加）
        changes = Math.min(additions, deletions)
        additions = additions - changes
        deletions = deletions - changes
      }

      return { additions, deletions, changes }
    } catch (error) {
      console.error('统计差异失败:', error)
      return { additions: 0, deletions: 0, changes: 0 }
    }
  })

  // 生成差异HTML
  const generateDiffHtml = (fileName: string = 'document.txt'): string => {
    const left = leftContent()
    const right = rightContent()

    if (!left || !right) {
      return ''
    }

    try {
      // 检测文件类型以启用语法高亮
      const fileExtension = fileName.split('.').pop()?.toLowerCase() || 'txt'
      const languageMap: Record<string, string> = {
        md: 'markdown',
        js: 'javascript',
        ts: 'typescript',
        vue: 'vue',
        html: 'html',
        css: 'css',
        json: 'json',
        py: 'python',
        java: 'java',
        cpp: 'cpp',
        c: 'c',
        php: 'php',
        rb: 'ruby',
        go: 'go',
        rs: 'rust',
        sh: 'bash',
        sql: 'sql',
        xml: 'xml',
        yaml: 'yaml',
        yml: 'yaml',
      }

      const language = languageMap[fileExtension] || 'plaintext'

      // 生成diff
      const patch = createTwoFilesPatch('原始文档', '修改文档', left, right, '', '', {
        context: 3,
      })

      // 生成HTML with 语法高亮配置
      return html(patch, {
        drawFileList: false,
        matching: 'lines',
        outputFormat: outputFormat(),
        renderNothingWhenEmpty: false,
      })
    } catch (error) {
      console.error('生成差异HTML失败:', error)
      return ''
    }
  }

  return {
    diffStats,
    generateDiffHtml,
  }
}
